package com.yc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.yc.config.ContentScanConfig;
import com.yc.config.ContentScanProperties;
import com.yc.service.ContentScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
@EnableConfigurationProperties(ContentScanProperties.class)
@Import(value = {ContentScanConfig.class})
public class ContentScanServiceImpl implements ContentScanService {

    @Autowired
    Client client;

    @Override
    public Map<String, Object> greenImageScan(String imageUrl) {
        Map<String, Object> resultMap = new HashMap<>();
        // 创建RuntimeObject实例并设置运行参数
        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", imageUrl);
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        ImageModerationRequest request = new ImageModerationRequest();
        // 图片检测service：内容安全控制台图片增强版规则配置的serviceCode，示例：baselineCheck
        // 支持service请参考：https://help.aliyun.com/document_detail/467826.html?0#p-23b-o19-gff
        request.setService("baselineCheck");
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        ImageModerationResponse response = null;
        try {
            response = client.imageModerationWithOptions(request, runtime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (response != null) {
            if (response.getStatusCode() == 200) {
                ImageModerationResponseBody result = response.getBody();
                resultMap.put("imageUrl", imageUrl);
                resultMap.put("success", true);
                resultMap.put("response", result.getData());
                resultMap.put("labels", result.getData().getDataId());
                resultMap.put("reason", result.getData().getResult());
            } else {
                resultMap.put("success", false);
                resultMap.put("message", "Response not success. status: " + response.getStatusCode());

            }
        } else {
            resultMap.put("success", false);
            resultMap.put("message", "Response is null");
        }
        return resultMap;

    }

    @Override
    public Map<String, Object> greenTextScan(String content) {
        Map<String, Object> resultMap = new HashMap<>();
        if (content == null || content.trim().isEmpty()) {
            resultMap.put("success", false);
            resultMap.put("message", "Content is empty");
            return resultMap;
        }

        RuntimeOptions runtime = new RuntimeOptions();
        runtime.readTimeout = 10000;
        runtime.connectTimeout = 10000;

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);

        if (serviceParameters.getString("content").trim().isEmpty()) {
            resultMap.put("success", false);
            resultMap.put("message", "Content is empty");
            return resultMap;
        }

        TextModerationRequest textModerationRequest = new TextModerationRequest();
        textModerationRequest.setService("chat_detection");
        textModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);

            if (response != null) {
                if (response.getStatusCode() == 200) {
                    TextModerationResponseBody result = response.getBody();
                    resultMap.put("content", content);
                    resultMap.put("success", true);
                    resultMap.put("labels", result.getData().getLabels());
                    String reasonJson = result.getData().getReason();
                    if( !StringUtils.isEmpty(reasonJson)){
                        Map reasonMap = JSONArray.parseObject(reasonJson, Map.class);
                        // 将解析后的数据放入 resultMap
                        resultMap.put("riskLevel", reasonMap.get("riskLevel"));
                        resultMap.put("riskTips", reasonMap.get("riskTips"));
                        resultMap.put("riskWords", reasonMap.get("riskWords"));
                    }

                } else {
                    resultMap.put("success", false);
                    resultMap.put("message", "Response not success. status: " + response.getStatusCode());
                }
            }
        } catch (Exception e) {
            log.error("Error during text moderation: ", e);
            resultMap.put("success", false);
            resultMap.put("message", "Exception occurred: " + e.getMessage());
        }

        return resultMap;
    }

    @Async
    @Override
   public CompletableFuture<Map<String, Object>> greenTextScan(String content, boolean isAsync) {
        Map<String, Object> resultMap = greenTextScan(content);
        return CompletableFuture.completedFuture(resultMap);
    }
}
